package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.service.CourseCategoryService;
import com.xuecheng.model.dto.CourseCategoryTreeDto;
import com.xuecheng.model.po.CourseCategory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CourseCategoryControllerImpl implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {


        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);

        Map<String, CourseCategoryTreeDto> maptemp = courseCategoryTreeDtos.stream()
                .filter(item->!id.equals(item.getId()))
                .collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));

        List<CourseCategoryTreeDto> courseCategoryTreeDtoArrlist = new ArrayList<>();

        courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).forEach(item->{
            if(item.getParentid().equals(id)){
                courseCategoryTreeDtoArrlist.add(item);
            }
            CourseCategoryTreeDto courseCategoryTreeDto = maptemp.get(item.getParentid());

            if(courseCategoryTreeDto != null){
                if(courseCategoryTreeDto.getChlildrenTreeNodes()==null){
                    courseCategoryTreeDto.setChlildrenTreeNodes(new ArrayList<>());
                }
                courseCategoryTreeDto.getChlildrenTreeNodes().add(item);
            }

        });

        return courseCategoryTreeDtoArrlist;
    }
}
